package 剑指Offer.easy;

import java.util.ArrayList;
import java.util.List;

public class 顺时针打印矩阵 {
    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return null;
            }
            int rowSize = matrix.length, colSize = matrix[0].length;
            //标志是否访问
            boolean[][] visited = new boolean[rowSize][colSize];
            int size = rowSize * colSize;
            int[] result = new int[size];
            int curRow = 0, curCol = 0;
            //方向变量
            int[][] direction = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            int directionIndex = 0;
            for (int i = 0; i < size; i++) {
                result[i] = matrix[curRow][curCol];
                visited[curRow][curCol] = true;
                int nextRow = curRow + direction[directionIndex][0], nextCol = curCol + direction[directionIndex][1];
                //判断是否需要转向
                if (nextRow < 0 || nextRow >= rowSize || nextCol < 0 || nextCol >= colSize || visited[nextRow][nextCol]) {
                    directionIndex = (directionIndex + 1) % 4;
                }
                //确定实际的下一步
                curRow = curRow + direction[directionIndex][0];
                curCol = curCol + direction[directionIndex][1];
            }
            return result;
        }
    }
}
